package sindconsole.webapp.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Map;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping("/api/settings")
public class SettingsController {

    @GetMapping("/props")
    @RequiresRoles("admin")
    public Properties loadProps(@RequestParam(value = "path", defaultValue = "sindconsole.properties") String path) {
        Properties prop = new Properties();
        try(InputStream in = new FileInputStream(path)) {
            prop.load(in);
        } catch(IOException x) {
            log.error("", x);
            prop.clear();
        }
        return prop;
    }

    @PostMapping("/props")
    @RequiresRoles("admin")
    public Properties saveProps(@RequestParam(value = "path", defaultValue = "sindconsole.properties") String path,
                           @RequestBody Map<String, String> newProps) {
        Properties prop = new Properties();
        try(InputStream in = new FileInputStream(path)) {
            prop.load(in);
        } catch(IOException x) {
            throw new RuntimeException(x);
        }
        prop.putAll(newProps);
        try(OutputStream out = new FileOutputStream(path)) {
            prop.store(out, "");
        } catch(IOException x) {
            throw new RuntimeException(x);
        }
        return prop;
    }

}
